package com.masz;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author Ma.sz 2023/2/16 11:31
 */
public class ThreadPoolTest extends ThreadPoolExecutor {
    public ThreadPoolTest(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
        // 允许核心线程被回收
        this.allowCoreThreadTimeOut(true);
    }

    public static void main(String[] args) throws Exception{
        ThreadPoolTest pool = new ThreadPoolTest(2, 5, 1, TimeUnit.SECONDS, new LinkedBlockingQueue<>(3));
        System.out.println("0 "+pool.getPoolSize());

        pool.execute(()->{
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
            }
        });
        System.out.println("1 "+pool.getPoolSize());

        pool.execute(()->{
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
            }
        });
        System.out.println("3 "+pool.getPoolSize());

        pool.execute(()->{
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
            }
        });
        System.out.println("4 "+pool.getPoolSize());

        pool.execute(()->{
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
            }
        });
        System.out.println("5 "+pool.getPoolSize());

        TimeUnit.SECONDS.sleep(10);
        System.out.println("end "+pool.getPoolSize()); // 存活时间过后，核心线程也被回收

        pool.execute(()->{
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
            }
        });
        System.out.println("end 1 "+pool.getPoolSize());

        Thread.currentThread().join();
    }


}
